<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/15 上午9:20
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/15 上午9:20
 * @FilePath: G:/chain-link-api-front-admin/src/views/web3Tools/batchWallet\index.vue
 * @Description: 批量生成钱包地址
-->
<template>
  <div class="container">
    <div class="formBox">
      <el-form :model="ruleForm" label-width="auto" ref="ruleRef" label-position="right"
               style="max-width: 500px; " center>
        <el-form-item prop="chainId">
          <el-select v-model.trim="ruleForm.chainId" filterable>
            <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.chainId"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="createNumber">
          <el-input type="number" v-model.num.trim="ruleForm.createNumber" :placeholder="$t('message.WalletNumbers')"
                    @input="valueNumber"/>
        </el-form-item>
        <el-form-item style="display: flex; flex-direction: row;justify-content: space-between;align-items: center">
          <el-button type="primary" size="large" @click="onSubmit()">{{ $t('global.Submit') }}</el-button>
          <el-button type="default" size="large" @click="onExport()">{{ $t('button.Export') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <transition name="slide-fade">
      <div class="resBox" v-if="walletList.length > 0">
        <div class="content">
          <el-card class="item" v-for="(item, key) in walletList" :key="key">
            <div class="id">{{ key+1 }}</div>
            <qrcode-vue :value="item.qrUrl" :size="80" :options="qrData.qrOptions" style="margin-right: 10px"></qrcode-vue>
            <div class="right">
              <div class="top item_body">
                <el-input v-model="item.address" disabled style="max-width: 700px;width: 700px">
                  <template #prepend>{{t('tools.Address') }}</template>
                  <template #append>
                    <el-button type="primary"  @click="copyTextToClipboard(item.address)">{{t('button.Copy')}}</el-button>
                  </template>
                </el-input>
              </div>
              <div class="footer item_body">
                <el-input v-model="item.privateKey" disabled style="max-width: 700px; width: 700px">
                  <template #prepend>{{t('tools.PrivateKey') }}</template>
                  <template #append >
                    <el-button type="primary"  @click="copyTextToClipboard(item.privateKey)">{{t('button.Copy')}}</el-button>
                  </template>
                </el-input>
              </div>
              <el-divider />
            </div>
          </el-card>
        </div>
      </div>
    </transition>
  </div>


</template>

<script setup>
import {ref, unref, reactive, onMounted} from "vue";
import {ElPagination, ElMessage, ElTable, ElMessageBox} from "element-plus";
import {getConfigList} from '@/require/api.js'
import {useClipboard} from '@vueuse/core'
import {useI18n} from "vue-i18n";
import {ethers} from "ethers";
import QrcodeVue from 'qrcode.vue';
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
const {t} = useI18n();

onMounted(() => {
  getChainList() // 获取链列表
})

const chainList = ref([])

// 表单数据
const ruleForm = reactive({
  createNumber: '',
  inpValue: '',
  chainId: ''
})

const walletList = ref([])

// 批量生成地址
// 批量生成三个地址
async function onSubmit() {
  walletList.value = []
  for (let i = 0; i < ruleForm.createNumber; i++) {
    const wallet = ethers.Wallet.createRandom();
    console.log(wallet)
    walletList.value.push({
      address: wallet.address,
      privateKey: wallet.privateKey,
      qrUrl : wallet.privateKey
    });
  }

  console.log(walletList.value)
}

// 导出
async function onExport() {
  // 准备数据
  const data = [
    ["Address", "Private Key"], // 表头
    ...walletList.value.map(wallet => [wallet.address, wallet.privateKey]) // 数据行
  ];

  // 创建工作表
  const worksheet = XLSX.utils.aoa_to_sheet(data);

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Wallets');

  // 生成Excel文件
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

  // 创建Blob对象
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });

  // 保存文件
  FileSaver.saveAs(blob, 'wallets.xlsx');
}

// 获取配置信息
async function getChainList() {
  const {code, data, msg} = await getConfigList();
  chainList.value = data;
  console.log(chainList)
}

const valueNumber = () => {
  ruleForm.createNumber = ruleForm.createNumber.replace(/\D/g, '')
  console.log(ruleForm.createNumber)
}


// 当点击执行复制
const {text, copy, copied, isSupported} = useClipboard({legacy: true})
const copyTextToClipboard = async (val) => {
  console.log(val)
  try {
    await copy(unref(val));
    ElMessage.success(t('message.CopySuccess'));
  } catch (err) {
    console.error('Failed to copy text: ', err);
  }
};

const qrData = reactive({
  qrUrl: [],
  qrOptions: {
    /*
    二维码选项，可以根据需要进行配置
    L: 约 7% 或更少的错误能被纠正。
    M: 约 15% 或更少的错误能被纠正。
    Q: 约 25% 或更少的错误能被纠正。
    H: 约 30% 或更少的错误能被纠正。纠错能力越高，二维码的密集度也越高，但生成的二维码尺寸会相应增加。
    margin: 表示二维码的外边距，即二维码图案到画布边缘的距离，以模块为单位。默认为 4 个模块，可根据需要增加或减少
    scale: 表示二维码的放大倍数。默认为 4，意味着每个模块（方块）会被放大为 4 像素。增大放大倍数可以生成更大尺寸的二维码，也可以增加二维码的可读性，但会增加生成的二维码图像的尺寸
    */
    errorCorrectionLevel: 'H',
    margin: 2,
    scale: 4,
  }
})
</script>

<style scoped lang="less">
:deep(.el-select__wrapper) {
  width: 300px;
  height: 50px;
}

:deep(.el-input) {
  width: 300px;
  height: 50px;
}

:deep(.el-form-item__content) {
  display: flex;
  justify-content: space-between;
}

.container {
  //height: calc(100vh - 100px);
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  background-color: #2b313c;

  .formBox {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .resBox {
    width: 100%;
    height: 800px;
    background-color: #f3f3f3;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;
    overflow-y: auto;

    .content {
      width: 80%;
      height: 1200px;
      background-color: #fff;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 30px;
      box-sizing: border-box;
      overflow-x: hidden;

      .item {
        width: 90%;
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        position: relative;

        .id{
          width: 20px;
          height: 20px;
          display: flex;
          flex-direction: row;
          justify-content: center;
          align-items: center;
          background-color: red;
          border-radius: 10px;
          color:#fff;
          position: absolute;
          top: 31px;
          left: 70px;
        }

        .item_body {
          display: flex;
          flex-direction: row;
          justify-content: flex-start;
          align-items: center;
          padding: 10px;
          box-sizing: border-box;
          margin-bottom: 5px;

          .title {
            margin-right: 50px;
          }
        }
      }
    }

  }

}

.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(30px);
  opacity: 0;
}


</style>